package com.merceria

import java.text.SimpleDateFormat;

import grails.converters.JSON;
import groovy.json.JsonBuilder;

import org.springframework.dao.DataIntegrityViolationException

class VentaSemanaController {
  //Test charly
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }

    def list(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        [ventaSemanaListInstance: VentaSemana.list(params), ventaSemanaInstanceTotal: VentaSemana.count()]
    }
	
    def create() {
        [ventaSemanaInstance: new VentaSemana(params)]
    }

    def save() {
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd")
		
        def ventaSemanaInstance = new VentaSemana(params)
		
		def ultimo = VentaSemana.withCriteria{
			order('semana', 'desc')
		}[0] 
		
		ventaSemanaInstance.semana = ultimo ? ultimo?.semana + 1 : 0
		ventaSemanaInstance.desde = sdf.parse(params.fechaInicio)
		ventaSemanaInstance.hasta = sdf.parse(params.fechaFin)
		ventaSemanaInstance.ingresoTotal = params.ingresoTotal.toFloat()//en algun momento se va a arreglar
		
		ventaSemanaInstance.fechaCreacion = new Date()
		
        if (!ventaSemanaInstance.save(flush: true)) {
            render(view: "create", model: [ventaSemanaInstance: ventaSemanaInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'ventaSemana.label', default: 'VentaSemana'), ventaSemanaInstance.id])
        redirect(action: "show", id: ventaSemanaInstance.id)
    }

    def show(Long id) {
        def ventaSemanaInstance = VentaSemana.get(id)
        if (!ventaSemanaInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'ventaSemana.label', default: 'VentaSemana'), id])
            redirect(action: "list")
            return
        }

        [ventaSemanaInstance: ventaSemanaInstance]
    }

    def edit(Long id) {
        def ventaSemanaInstance = VentaSemana.get(id)
        if (!ventaSemanaInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'ventaSemana.label', default: 'VentaSemana'), id])
            redirect(action: "list")
            return
        }
		
		def itemVentaListInstance = ItemVenta.findAllByVentaSemana(ventaSemanaInstance)

        [ventaSemanaInstance: ventaSemanaInstance, itemVentaListInstance:itemVentaListInstance]
    }
	
	def buscarArticulo()
	{
		def articulos = Articulo.findAll()
		
		def listaArt = [:]
		def artMap = [:]
		
		articulos.each {
			artMap = [:]
			artMap['id'] = it.id
			artMap['codigo'] = it.tipo.codigo
			artMap['numeroArticulo'] = it.numeroArticulo
			artMap['descripcion'] = it.descripcion
			artMap['precioCompleto'] = it.precioCompleto
			artMap['precioFraccion'] = it.precioFraccion
			artMap['fraccionable'] = it.fraccionable
			listaArt[it.id] = artMap
		}
		
		render listaArt as JSON
	}
	
	def addItemVenta()
	{
		def ventaSemanaInstance = VentaSemana.get(params.ventaId)
		
		if(!ventaSemanaInstance)
		{
			//ver q hace falta para q ajax muestre error
			flash.message = "No se encontro una venta para agregar el item."
			return
		}

		def articuloInstance = Articulo.get(params.idArt)
		
		if(!articuloInstance)
		{
			//ver q hace falta para q ajax muestre error
			flash.message = "No se encontro una articulo."
			return
		}
		
		ItemVenta item = new ItemVenta()
		
		item.codigoArticulo = articuloInstance.tipo.codigo
		item.numeroArticulo = articuloInstance.numeroArticulo
		item.descripcion = articuloInstance.descripcion
		
		def montoAcobrar
		def cantidadVendida = params.cantidad.toLong()
		
		if(articuloInstance.fraccionable)
		{
			item.costo = articuloInstance.costoFraccion
			item.precio = articuloInstance.precioFraccion
			montoAcobrar = articuloInstance.precioFraccion * cantidadVendida
			
		}else
	    {
			item.costo = articuloInstance.costoCompleto
			item.precio = articuloInstance.precioCompleto
			montoAcobrar = articuloInstance.precioCompleto * cantidadVendida
		}
		
		item.cantidad = params.cantidad.toLong()
        item.cobrado = params.cobrado.toFloat()			
		item.fraccion = articuloInstance.fraccionable
		item.ventaSemana = ventaSemanaInstance
		
		if(!item.save(flush:true))
		{
			flash.message = "error no se pudo guardar."
		}
		
		render item as JSON
	}
	
	def deleteItemVenta(Long id)
	{
		def itemVentaInstance = ItemVenta.get(id)
		
		if(!itemVentaInstance.delete(flush:true))
		{
			flash.message = "El item no pudo ser borrado."
		}
		
		render itemVentaInstance as JSON
	}

    def update(Long id, Long version) {
        def ventaSemanaInstance = VentaSemana.get(id)
        if (!ventaSemanaInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'ventaSemana.label', default: 'VentaSemana'), id])
            redirect(action: "list")
            return
        }

        if (version != null) {
            if (ventaSemanaInstance.version > version) {
                ventaSemanaInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'ventaSemana.label', default: 'VentaSemana')] as Object[],
                          "Another user has updated this VentaSemana while you were editing")
                render(view: "edit", model: [ventaSemanaInstance: ventaSemanaInstance])
                return
            }
        }

        ventaSemanaInstance.properties = params

        if (!ventaSemanaInstance.save(flush: true)) {
            render(view: "edit", model: [ventaSemanaInstance: ventaSemanaInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'ventaSemana.label', default: 'VentaSemana'), ventaSemanaInstance.id])
        redirect(action: "show", id: ventaSemanaInstance.id)
    }

    def delete(Long id) {
        def ventaSemanaInstance = VentaSemana.get(id)
        if (!ventaSemanaInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'ventaSemana.label', default: 'VentaSemana'), id])
            redirect(action: "list")
            return
        }

        try {
            ventaSemanaInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'ventaSemana.label', default: 'VentaSemana'), id])
            //redirect(action: "list")
			render ventaSemanaInstance as JSON
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'ventaSemana.label', default: 'VentaSemana'), id])
            redirect(action: "show", id: id)
        }
    }
}
